<template>
  <view class="download-history-page">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="navigateBack">
        <view class="icon icon-left" style="font-size: 28px; color: #333;">‹</view>
      </view>
      <view class="title">下载历史</view>
      <view class="placeholder"></view>
    </view>
    
    <!-- 下载历史列表 -->
    <wallpaper-grid 
      :wallpaper-list="downloads" 
      :has-more="hasMore" 
      :load-status="loadStatus"
      @wallpaper-click="navigateToDetail"
      @load-more="loadMore"
      @favorite="handleFavorite"
    />
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { useToken } from '@/common/token.js';
import WallpaperGrid from '../../components/wallpaper-grid.vue';

// 状态管理
const downloads = ref([]);
const page = ref(1);
const size = ref(20);
const hasMore = ref(true);
const loadStatus = ref('more');
const { token, isValid, loadToken } = useToken();

onLoad(() => {
  console.log('下载历史页面加载，重新加载token...');
  loadToken();
});

onShow(() => {
  console.log('下载历史页面显示，当前token状态:', {
    hasToken: !!token.value,
    tokenValid: isValid(),
    tokenLength: token.value ? token.value.length : 0
  });
  
  // 每次显示页面时重新加载token和数据
  loadToken();
  page.value = 1;
  downloads.value = [];
  hasMore.value = true;
  loadStatus.value = 'more';
  loadDownloadHistory();
});

// 加载下载历史
const loadDownloadHistory = async () => {
  try {
    uni.showLoading({ title: '加载中' });
    
    console.log('调用usergetDownloads云函数，传递的token:', {
      hasToken: !!token.value,
      tokenValid: isValid(),
      tokenLength: token.value ? token.value.length : 0
    });
    
    const res = await uniCloud.callFunction({
      name: 'usergetDownloads',
      data: {
        page: page.value,
        size: size.value,
        uniIdToken: token.value
      }
    });
    
    console.log('usergetDownloads云函数返回结果:', res.result);
    
    if (res.result.code === 0) {
      if (page.value === 1) {
        downloads.value = res.result.data.list;
      } else {
        downloads.value = [...downloads.value, ...res.result.data.list];
      }
      
      hasMore.value = res.result.data.hasMore;
      
      if (res.result.data.list.length === 0 && page.value === 1) {
        loadStatus.value = 'empty';
      } else {
        loadStatus.value = 'more';
      }
    } else if (res.result.code === 401) {
      // 用户未登录或登录过期，根据token状态决定处理方式
      console.log('接收到401错误，token状态:', res.result.tokenStatus);
      
      // 如果是token过期或错误，先尝试刷新token再决定是否跳转
      if (res.result.tokenStatus === 'expired' || res.result.tokenStatus === 'error') {
        console.log('token可能过期或错误，尝试刷新后重试...');
        refreshTokenAndReload();
      } else {
        // 如果确实是未提供token，则跳转到登录页面
        console.log('确实未登录，跳转到登录页面');
        uni.navigateTo({
          url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
        });
      }
    } else {
      uni.showToast({ title: res.result.message || '加载失败', icon: 'none' });
    }
  } catch (error) {
    console.error('加载下载历史失败:', error);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// 刷新token并重新尝试加载
const refreshTokenAndReload = async () => {
  try {
    console.log('尝试刷新token...');
    loadToken();
    // 延迟一点时间让token加载完成
    await new Promise(resolve => setTimeout(resolve, 100));
    if (token.value) {
      loadDownloadHistory();
    } else {
      console.log('刷新后仍无token，跳转到登录页面');
      uni.navigateTo({
        url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
      });
    }
  } catch (error) {
    console.error('刷新token失败:', error);
    uni.navigateTo({
      url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
    });
  }
};

// 加载更多
const loadMore = () => {
  if (!hasMore.value || loadStatus.value === 'loading') return;
  
  loadStatus.value = 'loading';
  page.value++;
  loadDownloadHistory();
};

// 处理收藏
const handleFavorite = (updatedWallpaper) => {
  // 更新下载历史中的收藏状态
  const index = downloads.value.findIndex(item => item._id === updatedWallpaper._id);
  if (index !== -1) {
    downloads.value[index].is_favorite = updatedWallpaper.is_favorite;
    downloads.value[index].favorite_count = updatedWallpaper.favorite_count;
  }
};

// 导航到详情页
const navigateToDetail = (wallpaper) => {
  uni.navigateTo({
    url: `/pages/detail/detail?id=${wallpaper._id}`
  });
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};
</script>

<style scoped lang="less">
.download-history-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    background-color: #fff;
    padding: 0 16px;
    border-bottom: 1px solid #eee;
    
    .back-btn {
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .title {
      font-size: 18px;
      font-weight: 500;
      color: #333;
    }
    
    .placeholder {
      width: 40px;
    }
  }
}
</style>